package yang.yu.sunny.service.impl;

import org.dayatang.domain.InstanceFactory;
import org.dayatang.utils.BeanUtils;
import yang.yu.sunny.domain.sales.Order;
import yang.yu.sunny.domain.sales.OrderItem;
import yang.yu.sunny.infra.elasticsearch.CustomerSearcher;
import yang.yu.sunny.infra.elasticsearch.ProductCategorySearcher;
import yang.yu.sunny.infra.elasticsearch.ProductSearcher;
import yang.yu.sunny.infra.persistence.sales.OrderItemMapper;
import yang.yu.sunny.infra.persistence.sales.OrderMapper;
import yang.yu.sunny.service.OrderDto;

import java.util.List;

/**
 * Created by yyang on 16/4/11.
 */
public class OrderAssembler {

    private ProductCategorySearcher categorySearcher;
    private ProductSearcher productSearcher;
    private CustomerSearcher customerSearcher;

    public OrderAssembler(ProductCategorySearcher categorySearcher,
                          ProductSearcher productSearcher,
                          CustomerSearcher customerSearcher) {
        this.categorySearcher = categorySearcher;
        this.productSearcher = productSearcher;
        this.customerSearcher = customerSearcher;
    }

    public OrderDto toDto(Order order) {
        OrderDto result = new OrderDto();
        new BeanUtils(result).copyPropertiesFrom(order);
        result.setCustomerName(customerSearcher.get(order.getCustomerId()).getName());
        OrderItemMapper mapper = InstanceFactory.getInstance(OrderItemMapper.class);
        List<OrderItem> items = mapper.findByOrder(order.getId());
        result.setItems(new OrderItemAssembler(categorySearcher, productSearcher).toDto(items));
        return result;
    }
}
